<!--
 * @Descripttion:分时销售报表
 * @Author: 森哥
 * @Date: 2022-11-08 14:14:27
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-09-22 11:01:47
-->
<template>
  <div>
    <div class="time-division-content-wrap">
      <!-- 左边盒子 -->
      <div class="left-box">
        <div class="left-box-title">分时销售报表</div>
        <!-- 头部查询项 -->
        <div class="left-box-search-box" :class="{ 'left-box-search-box-active': timeList }">
          <!-- 按钮组筛选项 -->
          <div class="paging-list-box">
            <div
              class="paging-list-item"
              v-for="(pagingItem, pagingIndex) in pagingList"
              :class="{ 'paging-list-item-active': pagingActiveIndex === pagingIndex }"
              :key="pagingIndex"
              @click="handleSelectPaging(pagingIndex)"
            >
              {{ pagingItem.name }}
            </div>
            <div class="paging-list-btn">
              <img
                class="right-btn"
                @click="queryCant(false)"
                src="@/assets/images/home/page-left-icon.png"
                alt=""
              />
              <img
                class="right-btn"
                @click="queryCant(true)"
                src="@/assets/images/home/page-right-icon.png"
                alt=""
              />
            </div>
          </div>
          <div class="search-box">
            <el-date-picker
              v-model="dateRangeList"
              type="daterange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD "
              :picker-options="pickerOptions"
              @change="onSearch"
              :disabled-date="disabledDate"
            ></el-date-picker>
          </div>
        </div>
        <!-- 循环项 -->
        <div
          class="list-box-wrap"
          :class="{ 'list-box-wrap-active': timeList }"
          v-loading="leftLoading"
          element-loading-text="加载中..."
        >
          <div class="list-box">
            <div
              v-for="(item, index) in list"
              class="list-item"
              :key="index"
              :class="{ 'list-item-active': timeReportId === item.id }"
              @click="handleSelectItem(item)"
            >
              <div class="list-header-box">
                <span class="type">{{ item.category.name }}</span>
                <span class="specification">{{ item.capacity }}人</span>
              </div>
              <div class="num">
                {{ item.name }}
              </div>
              <div class="money-box" v-if="item.pay_money">
                <img src="@/assets/images/bill/money.png" alt="" />
                <span class="money">
                  {{ item.pay_money }}
                </span>
              </div>
              <div></div>
            </div>
          </div>
        </div>
      </div>
      <!-- 右边盒子 -->
      <div class="right-box" v-if="timeList || rightLoading">
        <TimeDivisionSaleCard
          :timeList="timeList"
          :timeReportId="timeReportId"
          :loading="rightLoading"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import TimeDivisionSaleCard from './components/TimeDivisionSaleCard.vue'
import { fetchCategoryList } from '@/api/desktop.ts'
import { getNowDateAndTime } from '@/utils/index'
import { timeReport, timeTable } from '@/api/time.ts'
import { ElMessage } from 'element-plus'

// 响应式数据
const pagingList = ref([])
const searchParam = reactive({})
const pagingActiveIndex = ref(-1)
const pageSize = ref(1)
const total = ref(0)
const isFeach = ref(false)
const timeList = ref(null)
const list = ref([])
const timeReportId = ref('')
const dateRangeList = ref([])
const choiceDate0 = ref('')
// 加载状态
const leftLoading = ref(false)
const rightLoading = ref(false)

// 日期选择器选项
const pickerOptions = reactive({
  onPick: ({ maxDate, minDate }) => {
    choiceDate0.value = minDate ? minDate.getTime() : ''
    if (maxDate) {
      choiceDate0.value = ''
    }
  },
  disabledDate: time => {
    if (choiceDate0.value) {
      const choiceDateTime = new Date(choiceDate0.value).getTime()
      const preDate = new Date(choiceDateTime).getTime()
      const nextDate = new Date(choiceDateTime).getTime()
      return time.getTime() < preDate || time.getTime() > nextDate
    }
    return false
  }
})

// 限制只能选择同一天
const disabledDate = time => {
  if (choiceDate0.value) {
    const selectedDate = new Date(choiceDate0.value)
    const currentDate = new Date(time)

    // 只允许选择与已选日期相同的日期
    return currentDate.getTime() !== selectedDate.getTime()
  }
  return false
}

// 生命周期钩子
onMounted(() => {
  const { currentNowDate } = getNowDateAndTime()
  dateRangeList.value = [currentNowDate + ' ', currentNowDate + ' ']
  fetchCategoryListAsync().then(() => {
    timeTableAsync()
  })
})

// 方法定义
function handleSelectPaging(index) {
  pagingActiveIndex.value = index
  timeTableAsync()
}

function queryCant(type) {
  if (type) {
    pageSize.value++
    fetchCategoryListAsync().then(() => {
      // this.timeTable()
    })
  } else {
    isFeach.value = false
    pageSize.value--
    if (pageSize.value <= 0) {
      pageSize.value = 1
      return
    }
    fetchCategoryListAsync().then(() => {
      // this.timeTable()
    })
  }
}

async function fetchCategoryListAsync() {
  if (isFeach.value) {
    throw new Error('正在获取数据')
  }
  leftLoading.value = true
  try {
    const res = await fetchCategoryList({ page: pageSize.value, limit: 4 })
    if (res.data.data.length === 0) {
      isFeach.value = true
      return
    }
    pagingActiveIndex.value = 0
    total.value = res.data.total
    pagingList.value = [{ id: '', name: '全部' }, ...res.data.data]
    timeTableAsync()
  } catch (error) {
    ElMessage.error('获取分类列表失败: ' + error.message)
  } finally {
    leftLoading.value = false
  }
}

function handleSelectItem(item) {
  timeReportId.value = item.id
  timeReportAsync()
}

function onSearch() {
  // 确保开始日期和结束日期是同一天
  if (dateRangeList.value && dateRangeList.value.length === 2) {
    const startDate = dateRangeList.value[0]
    const endDate = dateRangeList.value[1]

    // 如果开始日期和结束日期不同，将结束日期设置为开始日期
    if (startDate !== endDate) {
      dateRangeList.value = [startDate, startDate]
    }
  }
  timeReportAsync()
}

// 获取详情信息
async function timeReportAsync() {
  let start_time = ''
  let end_time = ''
  if (dateRangeList.value) {
    start_time = dateRangeList.value[0] + '00:00:00'
    end_time = dateRangeList.value[1] + '23:59:59'
  }
  rightLoading.value = true
  try {
    const res = await timeReport({
      start_time,
      end_time,
      desk_id: timeReportId.value,
      print: '0'
    })

    if (!(res.data instanceof Array)) {
      timeList.value = res.data.detail
    } else {
      timeList.value = null
      ElMessage.error('暂无数据')
    }
  } catch (error) {
    ElMessage.error('获取报表数据失败: ' + error.message)
    timeList.value = null
  } finally {
    rightLoading.value = false
  }
}

async function timeTableAsync() {
  let start_time = ''
  let end_time = ''
  if (dateRangeList.value) {
    start_time = dateRangeList.value[0] + '00:00:00'
    end_time = dateRangeList.value[1] + '23:59:59'
  }
  leftLoading.value = true
  try {
    const res = await timeTable({
      start_time,
      end_time,
      category_id: pagingList.value[pagingActiveIndex.value]?.id
    })
    list.value = res.data.list
  } catch (error) {
    ElMessage.error('获取桌台列表失败: ' + error.message)
  } finally {
    leftLoading.value = false
  }
}
</script>

<style lang="scss" src="./modules/timeDivisionSale.scss" scoped></style>
